
const express = require('express');

import { Express } from 'express';
import { readdirSync } from 'fs';
import { join } from 'path';
// import { request } from 'http';


const app: Express = express();

const compression = require('compression');


// gzip压缩
app.use(compression());

app.use(express.static(join(__dirname, 'public')));

// 跨域
app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Accept");
    res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    if (req.method === 'OPTIONS') {
        res.end();
    } else {
        next();
    }
});

app.use(express.urlencoded({ extended: false }));
app.use(express.json());

readdirSync(join(__dirname, 'modules')).forEach((file: String) => {
    if (!(file.endsWith('.ts') || file.endsWith('.js'))) return;

    let route = file.replace(/\.ts|\.js/, '').replace(/_/g, '/');

    let module: Function = require(join(__dirname, 'modules', file.toString()));

    app.use('/' + route, async (req, res) => {

        try {
            if (typeof module === 'function') {
                var result: object | string = await module(req.query, req.body);
            }
        } catch (err) {
            res.status(500).json({
                err,
                msg: '服务器内部错误',
                code: 500
            })
            return;
        }

        res.json(result['data']);
    });

});

app.listen(3000, () => {
    console.log('服务器启动成功');
});
